package com.chenchu.job;

import com.chenchu.mapper.UserMobilePlanMapper;
import com.chenchu.model.UserMobilePlanDto;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class testXxlJob {

    @Autowired
    private UserMobilePlanMapper userMobilePlanMapper;


    /**
     * 普通测试
     * @throws Exception
     */
    @XxlJob("testJobHandler")
    public void testJobHandler() throws Exception {
        System.out.println("testJobHandler, 执行时间：" + new Date());
    }

    /**
     * 单机模式测试
     * @throws Exception
     */
    @XxlJob("sendMsgHandler")
    public void sendMsgHandler() throws Exception{
        System.out.println("sendMsgHandler, 执行时间：" + new Date());
        List<UserMobilePlanDto> userMobilePlans = null;
        try {
            userMobilePlans = userMobilePlanMapper.selectAll();
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
        System.out.println("任务开始时间:"+new Date()+",处理任务数量:"+userMobilePlans.size());
        Long startTime = System.currentTimeMillis();
        userMobilePlans.forEach(item->{
            try {
                //模拟发送短信动作
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("任务结束时间:"+new Date());
        System.out.println("任务耗时:"+(System.currentTimeMillis()-startTime)+"毫秒");
    }


    /**
     * 分片模式测试
     * @throws Exception
     */
    @XxlJob("sendMsgShardingHandler")
    public void sendMsgShardingHandler() throws Exception{
        System.out.println("sendMsgShardingHandler, 执行时间：" + new Date());
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        System.out.println("分片参数：当前分片序号 = "+ shardIndex +", 总分片数 = " + shardTotal);
        List<UserMobilePlanDto> userMobilePlans = null;
        if(shardTotal==1){
            //如果没有分片就直接查询所有数据
            userMobilePlans = userMobilePlanMapper.selectAll();
            System.out.println("没有多台机器由一台完成，查询全部数据");
        }else{
            userMobilePlans = userMobilePlanMapper.selectByMod(shardIndex,shardTotal);
            System.out.println("有多台机器完成，通过取模获取每个机器对应应该发送的数量");
        }
        System.out.println("处理任务数量:"+userMobilePlans.size());
        Long startTime = System.currentTimeMillis();
        userMobilePlans.forEach(item->{
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("任务结束时间:"+new Date());
        System.out.println("任务耗时:"+(System.currentTimeMillis()-startTime)+"毫秒");
    }
}
